﻿using AutoMapper;
using MediatR;
using ProductionLine.API.Application.Command.BOM;
using ProductionLine.Domain.BOM;
using ProductionLine.Domain.Plan;
using ProductionLine.ErrorCode;
using ProductionLine.Infrastructure.Implement;
using ProductionLine.Infrastructure.Interface;

namespace ProductionLine.API.Application.Handler.BOM
{
    public class AddBOMHandler : IRequestHandler<AddBOMCommand, APIResult<int>>
    {
        IMapper mapper;
        DatabaseContext db;
        IBaseRepository<PlanModel> planRepo;

        public AddBOMHandler(IMapper mapper, DatabaseContext db, IBaseRepository<PlanModel> planRepo)
        {
            this.mapper = mapper;
            this.db = db;
            this.planRepo = planRepo;
        }

        public async Task<APIResult<int>> Handle(AddBOMCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = mapper.Map<BOMModel>(request);
            int r = db.SqlSugar.Insertable(model).ExecuteCommand();
            if (r > 0)
            {
                res.Msg = "添加BOM成功";
                res.Data = r;
                res.Code = APIEnum.Success;
                // 修改后的后端代码
                var planstate = planRepo.GetAll().Where(c => c.PlanId == model.PlanId && !c.IsDel).FirstOrDefault();
                if (planstate != null)
                {
                    planstate.PlanState = 1;
                    db.SqlSugar.Updateable(planstate).ExecuteCommand();
                }
            }
            else
            {
                res.Msg = "添加BOM失败";
                res.Data = r;
                res.Code = APIEnum.Fail;
            }
                return await Task.FromResult(res);
        }
    }
}
